package com.eu.ebpm.engine.cmd.pvm;

import java.util.Date;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.eu.ebpm.engine.entity.args.Param;
import com.eu.ebpm.engine.entity.deploy.Mission;
import com.eu.ebpm.engine.entity.deploy.Transfer;
import com.eu.ebpm.engine.entity.history.HisTask;
import com.eu.ebpm.engine.entity.runtime.TaskEntity;
import com.eu.ebpm.engine.repository.ExecutionRepository;
import com.eu.ebpm.engine.repository.ExecutionVariableRepository;
import com.eu.ebpm.engine.repository.HisExecutionRepository;
import com.eu.ebpm.engine.repository.HisTaskRepository;

/**
 * 
 * @author 王晓华
 */
@Component
public class SubEndEventIntoCommand {

	@Autowired
	private ExecutionRepository executionRepository;
	
	@Autowired
	private HisExecutionRepository hisExecutionRepository;
	
	@Autowired
	private HisTaskRepository hisTaskRepository;
	
	@Autowired
	private ExecutionVariableRepository executionVariableRepository;

	public void execute(Mission mission, TaskEntity task, Map<String, Object> variables, Transfer nextTransfer) {
		
		// 1、插入历史任务表；历史执行流程表
		long subExecutionId = task.getExecutionId();
		hisTaskRepository.insert(new HisTask(mission.getType(), mission.getName(), mission.getDesc(), nextTransfer.getName(), subExecutionId, task.getRootExecutionId(), mission.getId(), null, null, new Date(), new Date()));
		executionRepository.updateHisExecution(Param.init("runStatus", false).add("dueTime", new Date()).put("id", subExecutionId));
		
		//2、 copy历史参数表；删除执行参数表
		executionVariableRepository.copyToHisExeVariable(Param.map("executionId", subExecutionId));
		executionVariableRepository.remove(subExecutionId, null);
		
		// 4、删除执行流程表
		executionRepository.delete(subExecutionId);
		
		// 3、将运行流程执行的ID设置回去父ID
		long parentExecutionId = hisExecutionRepository.queryParentId(subExecutionId);
		task.setExecutionId(parentExecutionId);
		
	}

}
